package zcw.com.lib_leet_code;

import java.util.Arrays;

import zcw.com.lib_leet_code.util.Util;

/**
 * Created by 朱城委 on 2021/7/14.<br><br>
 *
 * 两个数组的交集Ⅱ
 */
public class Topic350 {
    public static void main(String[] args) {
        Topic350 instance = new Topic350();

        int[] array1 = new int[] {1,2,2,1};
        int[] array2 = new int[] {2,2};
        Util.printArray(instance.intersect(array1, array2));

        array1 = new int[] {4,9,5};
        array2 = new int[] {9,4,9,8,4};
        Util.printArray(instance.intersect(array1, array2));
    }

    public int[] intersect(int[] nums1, int[] nums2) {
        int[] array = new int[1001];

        for(int value : nums1) {
            array[value]++;
        }

        int[] result = new int[Math.min(nums1.length, nums2.length)];
        int index = 0;
        for(int value : nums2) {
            if(array[value] > 0) {
                result[index++] = value;
                array[value]--;
            }
        }

        return Arrays.copyOf(result, index);
    }
}
